import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import VuexStore from '@/store/index'

const OriginPush=VueRouter.prototype.push;
VueRouter.prototype.push=function(location,onResolve,onReject){
  if(onResolve||onReject) return OriginPush.call(this,location,onResolve,onReject)
  //如果出现异常提示，不显示异常
  return OriginPush.call(this,location).catch(err=>err);
}

Vue.use(VueRouter)
Vue.prototype.back=function(){
  if(window.history.length>1){
    this.$router.back()
  }else{
    this.$router.push('/')
  }
}
const routes = [
  {
    path: '/',
    name: 'Home',
    meta:{
      tabbarshow:true,
    },
    component: Home
  },
  {
    path: '/category',
    name: 'Category',
    meta:{
      tabbarshow:true,
    },
    component: () => import('@/views/Category.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta:{
      tabbarshow:true, 
    },
    component: () => import('@/views/Cart.vue')
  },
  {
    path: '/user',
    name: 'User',
    meta:{needLogin:true,
      tabbarshow:true,
    },
    component: () => import('@/views/User.vue')
  },
  {
    path: '/search',
    name: 'Search',
    meta:{
      tabbarshow:true,
    },
    component: () => import('@/views/Search.vue')
  },
  {
    path:'/login',
    name:'Login',
    component:()=>import('@/views/Login.vue')
  },
  {
    path:'/detail/:id',
    name:'Detail',
    meta:{
      title:"详情页",
      tabbarshow:false,
    },
    props:true,
    component:()=>import("@/views/Detail")
  },
  {
    path:'/newhot/:id',
    name:"NewHot",
    meta:{
      tabbarshow:false,
    },
    props:true,
    component:()=>import("@/views/NewHot")
  },
  {
    path:'/edit',
    name:"Edit",
    meta:{
      tabbarshow:false,
    },
    props:true,
    component:()=>import("@/views/Edit")
  },
  {
    path:"/address",
    name:"Address",
    meta:{
      tabbarshow:false,
    },
    // props:true,
    component:()=>import("@/views/Address")
  },
  {
    path:"/search/:keyword",
    name:"SearchEnd",
    // meta:{hideNav:true},
    props:true,
    component:()=>import('@/views/SearchEnd.vue')
  },
  {
    path:"/order",
    name:"Order",
    props:true,
    component:()=>import('@/views/Order.vue')
  },
  {
    path:"/buy",
    name:"Buy",
    meta:{needLogin:true,
    },
    component:()=>import('@/views/Buy.vue')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
// 全局路由守卫
router.beforeEach((to,from,next)=>{
// 拿取路由里面meta信息判断当前进入的路由是否需要
  if(to.meta.needLogin && !VuexStore.getters.LoginToken){
    next('/login')
  }
  next();
  // if(to.path==="/"){
  //   next()
  // }else{
  //   let token=localStorage.getItem("token");
  //   if(token==null||token===""){
  //     console.log("请先登录");
  //     next({name:"Login"});
  //   }else{
  //     next();
  //   }
  // }
})
export default router
